package term

import (
	"context"
	"strings"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/attachment/model"
	"mall/service/attachment/rpc/internal/svc"
	"mall/service/attachment/rpc/internal/utils"
	"mall/service/attachment/rpc/internal/utils/errorhandler"
	"mall/service/attachment/rpc/types/attachment"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetTermListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetTermListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetTermListLogic {
	return &BackendGetTermListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetTermListLogic) BackendGetTermList(in *attachment.TermListReq) (*attachment.TermListResp, error) {
	var orderBys []string
	if len(in.OrderBy) > 0 {
		for _, orderBy := range in.OrderBy {
			var order string = " ASC"
			if orderBy.Order == "1" {
				order = " DESC"
			}
			if orderBy.Field == "id" {
				orderBys = append(orderBys, model.AttachmentTermColumns.TermID+order)
			}
			if orderBy.Field == "sort" {
				orderBys = append(orderBys, model.AttachmentTermColumns.Sort+order)
			}
			if orderBy.Field == "createdAt" {
				orderBys = append(orderBys, model.AttachmentTermColumns.CreatedAt+order)
			}
		}
	}

	var stati string
	if len(in.FilterBy) > 0 {
		for _, filterBy := range in.FilterBy {
			if filterBy.Field == "status" {
				stati = filterBy.In
			}
		}
	}

	var page uint64
	var pageSize uint64
	var restricted bool
	filterMap := make(map[string]map[string][]any)
	resp := &attachment.TermListResp{}
	if in.Ids != nil {
		if vals := modelx.UniqueInterfaces(*in.Ids, 64); len(vals) == 0 {
			return resp, nil
		} else {
			filterMap[model.AttachmentTermColumns.TermID] = map[string][]any{
				"in": vals,
			}
			restricted = true
		}
	}

	if !restricted {
		page = in.Page
		pageSize = in.PageSize
	}

	statusIn := modelx.UniqueInterfaces(stati, 32)
	statusMap := make(map[string][]any)
	if len(statusIn) > 0 {
		statusMap["in"] = statusIn
	}
	if in.Status != nil {
		statusMap["equalTo"] = []any{*in.Status}
	}
	filterMap[model.AttachmentTermColumns.Status] = statusMap

	if in.Name != nil {
		filterMap[model.AttachmentTermColumns.Name] = map[string][]any{
			"contain": []any{strings.TrimSpace(*in.Name)},
		}
	}
	if in.Slug != nil {
		filterMap[model.AttachmentTermColumns.Slug] = map[string][]any{
			"equalTo": []any{strings.TrimSpace(*in.Slug)},
		}
	}
	if in.Taxonomy != nil {
		taxonomy := utils.ParseTaxonomy(strings.TrimSpace(*in.Taxonomy))
		filterMap[model.AttachmentTermColumns.Taxonomy] = map[string][]any{
			"equalTo": []any{taxonomy},
		}
	}
	if in.ParentId != nil {
		filterMap[model.AttachmentTermColumns.ParentID] = map[string][]any{
			"equalTo": []any{*in.ParentId},
		}
	}
	if in.GroupId != nil {
		filterMap[model.AttachmentTermColumns.TermGroup] = map[string][]any{
			"equalTo": []any{*in.GroupId},
		}
	}

	var startTimeIn []any
	var endTimeIn []any
	if in.StartTime != nil && len(strings.TrimSpace(*in.StartTime)) > 0 {
		if startTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.StartTime)); err == nil {
			startTimeIn = append(startTimeIn, startTime)
		}
	}
	if in.EndTime != nil && len(strings.TrimSpace(*in.EndTime)) > 0 {
		if endTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.EndTime)); err == nil {
			endTimeIn = append(endTimeIn, endTime)
		}
	}
	createdAtMap := make(map[string][]any)
	if len(startTimeIn) > 0 {
		createdAtMap["moreThan"] = startTimeIn
	}
	if len(endTimeIn) > 0 {
		createdAtMap["lessThanOrEqualTo"] = endTimeIn
	}
	filterMap[model.AttachmentTermColumns.CreatedAt] = createdAtMap

	var orderBy string
	if len(orderBys) > 0 {
		orderBy = strings.Join(orderBys, ",")
	} else {
		orderBy = model.AttachmentTermColumns.Sort
	}

	res, count, err := l.svcCtx.MediaTerm.GetList(l.ctx, model.M{
		"page":     page,
		"pageSize": pageSize,
		"orderBy":  orderBy,
	}, 1, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	resp.Total = uint64(count)
	for _, v := range res {
		resp.List = append(resp.List, &attachment.TermInfo{
			Id:           pointy.GetPointer(v.TermID),
			Name:         pointy.GetPointer(v.Name),
			Slug:         pointy.GetPointer(v.Slug),
			Taxonomy:     pointy.GetPointer(utils.FormatTaxonomy(int32(v.Taxonomy))),
			ParentId:     pointy.GetPointer(v.ParentID),
			GroupId:      pointy.GetPointer(uint32(v.TermGroup)),
			Desc:         pointy.GetPointer(v.Description),
			FilteredDesc: pointy.GetPointer(v.DescriptionFiltered),
			Sort:         pointy.GetPointer(uint32(v.Sort)),
			Status:       pointy.GetPointer(uint32(v.Status)),
			Count:        pointy.GetPointer(uint32(v.Count)),
			CreatedAt:    pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
			UpdatedAt:    pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
			DeletedAt:    pointy.GetPointer(modelx.FormatNullDotTime(v.DeletedAt, "")),
		})
	}

	return resp, nil
}
